import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _applyDecoratedDescriptor from "@babel/runtime/helpers/esm/applyDecoratedDescriptor";
import _isEmpty from "lodash/isEmpty";
import _isFunction from "lodash/isFunction";
var _excluded = ["data"];

var _dec, _dec2, _dec3, _dec4, _dec5, _dec6, _dec7, _dec8, _dec9, _dec10, _dec11, _dec12, _dec13, _class, _class2;

import React from 'react';
import { Dropdown, Form, Icon, Menu, Modal, notification, Tree } from 'antd';
import { Bind, Debounce } from 'lodash-decorators';
import { Button } from "../Permission";
import intl from "../../utils/intl";
import { getResponse, listenDownloadError } from "../../utils/utils";
import { downloadFile, initiateAsyncExport, queryColumn, queryIdpValue } from "../../services/api";
import ExportPage from "./ExportPage";
import HistoryData from "./HistoryData"; // 监听导出错误时 postMessage 事件

listenDownloadError('downloadError', intl.get('cpaas.common.notification.export.error').d('导出异常')); // 监听导出错误时 postMessage 事件

listenDownloadError('asyncRequestSuccess', intl.get('cpaas.common.notification.export.async').d('异步导出任务已提交'), 'success');
var TreeNode = Tree.TreeNode;
/**
 * 导出Excel ExcelExport
 *
 * @extends {PureComponent} - React.PureComponent
 * @reactProps {!string} [requestUrl=''] - 导出请求的url
 * @reactProps {?boolean} [defaultSelectAll=false] - 默认勾选所有列
 * @reactProps {?string} [method='GET'] - 导出请求的类型，默认GET请求
 * @reactProps {!object || function} [queryParams={}] - 表单查询参数，查询之后将会导出查询的数据, 可传递函数
 * @reactProps {?object} [queryFormItem={}] - 导出条件
 * @reactProps {?object} [otherButtonProps={}] - 导出按钮props
 * @reactProps {?array} [code = []] - 权限控制
 * @reactProps {?boolean} [exportAsync=false] - 是否有异步导出(租户层才会生效)
 * @returns React.element
 * @example
 * import ExcelExport from 'components/ExcelExport';
 *
 *   queryFormItem() {
 *    return (
 *      <React.Fragment>
 *        <FormItem label='事件编码'>
 *          {this.props.form.getFieldDecorator('eventCode', {
 *            initialValue: '',
 *          })(<Input style={{ width: '150px' }} />)}
 *        </FormItem>
 *        <FormItem label='事件描述'>
 *          {this.props.form.getFieldDecorator('eventDescription', {
 *            initialValue: '',
 *          })(<Input style={{ width: '150px' }} />)}
 *        </FormItem>
 *      </React.Fragment>
 *    );
 *   }
 *
 * <ExcelExport
 *  requestUrl={`${CPAAS_PLATFORM} /v1/events/export`}
 *  queryParams={this.props.form.getFieldsValue()}
 *  queryFormItem={this.queryFormItem()}
 * />
 */

var ExcelExport = (_dec = Form.create({
  fieldNameProp: null
}), _dec2 = Bind(), _dec3 = Bind(), _dec4 = Bind(), _dec5 = Bind(), _dec6 = Debounce(500), _dec7 = Bind(), _dec8 = Bind(), _dec9 = Bind(), _dec10 = Bind(), _dec11 = Bind(), _dec12 = Bind(), _dec13 = Bind(), _dec(_class = (_class2 = /*#__PURE__*/function (_React$PureComponent) {
  _inherits(ExcelExport, _React$PureComponent);

  var _super = _createSuper(ExcelExport);

  function ExcelExport(props) {
    var _this;

    _classCallCheck(this, ExcelExport);

    _this = _super.call(this, props);
    _this.state = {
      modalVisible: false,
      exportList: [],
      exportPending: false,
      fetchColumnLoading: true,
      enableAsync: false,
      // 允许异步
      // 树
      expandedKeys: [],
      // 展开的节点
      checkedKeys: [],
      // 选择的节点
      exportTypeList: [],
      // 导出类型值集
      // 异步数据
      historyModalVisible: false // 异步数据模态框显示

    };
    return _this;
  }
  /**
   * @function queryColumnData - 查询可以选择导出的列数据
   */


  _createClass(ExcelExport, [{
    key: "queryColumnData",
    value: function queryColumnData(config) {
      var _this2 = this;

      var _this$props = this.props,
          requestUrl = _this$props.requestUrl,
          _this$props$method = _this$props.method,
          method = _this$props$method === void 0 ? 'GET' : _this$props$method,
          _this$props$defaultSe = _this$props.defaultSelectAll,
          defaultSelectAll = _this$props$defaultSe === void 0 ? false : _this$props$defaultSe,
          form = _this$props.form;
      this.setState({
        fetchColumnLoading: true
      });
      queryColumn({
        requestUrl: requestUrl,
        method: method
      }).then(function (res) {
        var response = getResponse(res);
        var nextState = {};

        if (response && response.children) {
          var defaultList = [];

          if (defaultSelectAll) {
            var exTreeKey = function exTreeKey(data) {
              if (data) {
                defaultList.push(data.id);

                if (Array.isArray(data.children)) {
                  for (var i = 0; i < data.children.length; i++) {
                    exTreeKey(data.children[i]);
                  }
                }
              }
            };

            exTreeKey(res);
          } else {
            var travelTree = function travelTree(data) {
              if (data) {
                // 后端返回的是 boolean 值
                if (data.checked) {
                  defaultList.push(data.id);
                }

                if (Array.isArray(data.children)) {
                  for (var i = 0; i < data.children.length; i++) {
                    travelTree(data.children[i]);
                  }
                }
              }
            };

            travelTree(res);
          }

          nextState.exportList = [res];
          nextState.expandedKeys = ["".concat(res.id)];
          nextState.checkedKeys = defaultList;
        }

        nextState.enableAsync = !!response.enableAsync; // 不为真 就为假

        _this2.setState(nextState);

        if (!nextState.enableAsync) {
          if (form.getFieldValue('async') === 'true') {
            form.setFieldsValue({
              async: 'false'
            });
          }
        }
      }).finally(function () {
        _this2.setState({
          fetchColumnLoading: false
        });

        var exportList = _this2.state.exportList;

        if (!_isEmpty(config)) {
          _this2.traversalTreeNodes(exportList);

          _this2.handleExport(config);
        }
      });
    }
    /**
     * @function showModal - 控制对话框是否可见
     * @param {boolean} flag - 对话框显示标识
     */

  }, {
    key: "showModal",
    value: function showModal(flag) {
      var _this3 = this;

      var _this$props$defaultCo = this.props.defaultConfig,
          defaultConfig = _this$props$defaultCo === void 0 ? {} : _this$props$defaultCo;

      if (!_isEmpty(defaultConfig)) {
        var data = defaultConfig.data,
            others = _objectWithoutProperties(defaultConfig, _excluded);

        if (!_isEmpty(data)) {
          this.traversalTreeNodes(defaultConfig.data);
          this.handleExport(_objectSpread(_objectSpread({
            fillerType: 'single-sheet'
          }, others), {}, {
            async: 'false'
          }));
        } else {
          this.queryColumnData(_objectSpread(_objectSpread({
            fillerType: 'single-sheet'
          }, others), {}, {
            async: 'false'
          }));
        }
      } else {
        this.setState({
          modalVisible: flag,
          checkedKeys: []
        });

        if (flag) {
          queryIdpValue('CPFM.EXCEL_EXPORT_TYPE').then(function (res) {
            var response = getResponse(res);

            if (response) {
              _this3.setState({
                exportTypeList: res
              });
            }
          });
          this.queryColumnData();
        } else {
          this.setState({
            checkedKeys: []
          });
        }
      }
    }
    /**
     * @function handleExpand - 节点展开
     * @param {array} expandedKeys - 展开的节点组成的数组
     */

  }, {
    key: "handleExpand",
    value: function handleExpand(expandedKeys) {
      this.setState({
        expandedKeys: expandedKeys
      });
    }
    /**
     * @function handleSelect - 选择项变化监控
     * @param {array} checkedKeys - 选中项的 key 数组
     */

  }, {
    key: "handleSelect",
    value: function handleSelect(checkedKeys) {
      this.setState({
        checkedKeys: checkedKeys
      });
    }
    /**
     * @function handleExport - 导出，下载文件
     */

  }, {
    key: "handleExport",
    value: function handleExport() {
      var _this4 = this;

      var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      var _this$props2 = this.props,
          _this$props2$requestU = _this$props2.requestUrl,
          requestUrl = _this$props2$requestU === void 0 ? '' : _this$props2$requestU,
          _this$props2$queryPar = _this$props2.queryParams,
          queryParams = _this$props2$queryPar === void 0 ? {} : _this$props2$queryPar,
          form = _this$props2.form,
          _this$props2$method = _this$props2.method,
          method = _this$props2$method === void 0 ? 'GET' : _this$props2$method;
      var checkedKeys = this.state.checkedKeys;
      var queryData = queryParams;

      if (_isFunction(queryParams)) {
        queryData = queryParams();
      }

      var newQueryParams = _objectSpread(_objectSpread(_objectSpread({}, queryData), form.getFieldsValue()), config);

      if (!checkedKeys || Array.isArray(checkedKeys) && checkedKeys.length === 0) {
        Modal.warning({
          title: intl.get('cpaas.common.message.validation.atLeast').d('请至少选择一条数据')
        });
      } else {
        this.setState({
          exportPending: true
        });
        var params = checkedKeys.map(function (item) {
          return {
            name: 'ids',
            value: item
          };
        }); // 添加表单查询参数

        for (var _i = 0, _Object$keys = Object.keys(newQueryParams); _i < _Object$keys.length; _i++) {
          var key = _Object$keys[_i];

          if (newQueryParams[key] !== undefined) {
            params.push({
              name: key,
              value: newQueryParams[key]
            });
          }
        } // 添加导出Excel参数


        params.push({
          name: 'exportType',
          value: 'DATA'
        });

        if (newQueryParams.async === 'true') {
          initiateAsyncExport({
            requestUrl: requestUrl,
            queryParams: params
          }).then(function (res) {
            if (res) {
              notification.success({
                message: intl.get('cpaas.common.notification.export.asyncWithUid', {
                  uuid: res.uuid
                }).d("\u5F02\u6B65\u5BFC\u51FA\u4EFB\u52A1\u5DF2\u63D0\u4EA4".concat(res.uuid))
              });
            }

            _this4.setState({
              exportPending: false
            });
          });
        } else {
          downloadFile({
            requestUrl: requestUrl,
            queryParams: params,
            method: method
          }).then(function (res) {
            if (res) {
              _this4.setState({
                exportPending: false
              });

              if (!_isEmpty(config)) {
                _this4.setState({
                  checkedKeys: []
                });
              }
            }
          });
        }
      }
    }
    /**
     * @function traversalTreeNodes - 遍历树的子节点
     * @param {object} data - 列数据
     */

  }, {
    key: "traversalTreeNodes",
    value: function traversalTreeNodes() {
      var _this5 = this;

      var data = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
      var arr = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
      var checkedKeys = this.state.checkedKeys;
      var idList = arr;
      data.map(function (item) {
        var temp = item;
        checkedKeys.push(temp.id);

        _this5.setState({
          checkedKeys: checkedKeys
        });

        if (temp.children) {
          _this5.traversalTreeNodes(temp.children, idList);
        }

        return temp;
      });
    }
    /**
     * @function renderTreeNodes - 渲染树的子节点
     * @param {object} data - 列数据
     */

  }, {
    key: "renderTreeNodes",
    value: function renderTreeNodes(data) {
      var _this6 = this;

      return data.map(function (item) {
        if (item.children) {
          return /*#__PURE__*/React.createElement(TreeNode, {
            title: item.title,
            key: item.id,
            dataRef: item
          }, _this6.renderTreeNodes(item.children));
        }

        return /*#__PURE__*/React.createElement(TreeNode, Object.assign({}, item, {
          key: item.id
        }));
      });
    }
  }, {
    key: "renderQueryForm",
    value: function renderQueryForm() {
      var queryFormItem = this.props.queryFormItem;
      return /*#__PURE__*/React.createElement(Form, {
        layout: "inline"
      }, queryFormItem);
    }
  }, {
    key: "handleMenuClick",
    value: function handleMenuClick(_ref) {
      var key = _ref.key;

      if (key === 'async-data') {
        this.showHistoryModal();
      } else if (key === 'export') {
        this.showModal(true);
      }
    }
  }, {
    key: "showSyncExportModal",
    value: function showSyncExportModal() {
      this.showModal(true);
    }
  }, {
    key: "showHistoryModal",
    value: function showHistoryModal() {
      this.setState({
        historyModalVisible: true
      });
    }
  }, {
    key: "hideHistoryModal",
    value: function hideHistoryModal() {
      this.setState({
        historyModalVisible: false
      });
    }
  }, {
    key: "render",
    value: function render() {
      var _this7 = this;

      var _this$props3 = this.props,
          code = _this$props3.code,
          queryFormItem = _this$props3.queryFormItem,
          otherButtonProps = _this$props3.otherButtonProps,
          _this$props3$buttonTe = _this$props3.buttonText,
          buttonText = _this$props3$buttonTe === void 0 ? intl.get('cpaas.common.button.export').d('导出') : _this$props3$buttonTe,
          _this$props3$title = _this$props3.title,
          title = _this$props3$title === void 0 ? intl.get("cpaas.common.components.export").d('导出Excel') : _this$props3$title,
          form = _this$props3.form,
          _this$props3$exportAs = _this$props3.exportAsync,
          exportAsync = _this$props3$exportAs === void 0 ? false : _this$props3$exportAs,
          defaultConfig = _this$props3.defaultConfig;
      var _this$state = this.state,
          exportTypeList = _this$state.exportTypeList,
          exportList = _this$state.exportList,
          fetchColumnLoading = _this$state.fetchColumnLoading,
          checkedKeys = _this$state.checkedKeys,
          expandedKeys = _this$state.expandedKeys,
          enableAsync = _this$state.enableAsync,
          exportPending = _this$state.exportPending,
          modalVisible = _this$state.modalVisible,
          historyModalVisible = _this$state.historyModalVisible,
          queryHistoryLoading = _this$state.queryHistoryLoading;
      var modalProps = {
        title: title,
        destroyOnClose: true,
        bodyStyle: {
          height: '460px',
          overflowY: 'scroll'
        },
        visible: modalVisible,
        onCancel: this.showModal.bind(this, false),
        onOk: function onOk() {
          _this7.handleExport();
        },
        confirmLoading: exportPending
      };

      var buttonProps = _objectSpread(_objectSpread({
        code: code,
        icon: 'export',
        type: 'default'
      }, otherButtonProps), {}, {
        onClick: function onClick() {}
      });

      var formItemLayout = {
        labelCol: {
          span: 12
        },
        wrapperCol: {
          span: 12
        }
      };
      var historyModalProps = {
        title: intl.get('cpaas.common.excelExport.view.title.asyncData').d('异步数据'),
        visible: historyModalVisible,
        destroyOnClose: true,
        width: '1000px',
        onCancel: this.hideHistoryModal,
        onOk: this.hideHistoryModal,
        confirmLoading: queryHistoryLoading,
        wrapClassName: 'ant-modal-sidebar-right',
        transitionName: 'move-right'
      }; // 导出组件入口: 如果设置了 异步且为租户级, 那么显示异步数据(Dropdown),否则显示导出按钮

      var exportEntryElement = exportAsync && _isEmpty(defaultConfig) ? /*#__PURE__*/React.createElement(Dropdown, {
        overlay: /*#__PURE__*/React.createElement(Menu, {
          onClick: this.handleMenuClick
        }, /*#__PURE__*/React.createElement(Menu.Item, {
          key: "export"
        }, intl.get('cpaas.common.button.export').d('导出')), /*#__PURE__*/React.createElement(Menu.Item, {
          key: "async-data"
        }, intl.get('cpaas.common.excelExport.asyncDataView').d('异步数据查看')))
      }, /*#__PURE__*/React.createElement(Button, buttonProps, buttonText, /*#__PURE__*/React.createElement(Icon, {
        type: "down"
      }))) : /*#__PURE__*/React.createElement(Button, Object.assign({}, buttonProps, {
        onClick: this.showSyncExportModal,
        loading: exportPending
      }), buttonText);
      return /*#__PURE__*/React.createElement(React.Fragment, null, exportEntryElement, /*#__PURE__*/React.createElement(Modal, modalProps, /*#__PURE__*/React.createElement(ExportPage, {
        exportTypeList: exportTypeList,
        exportList: exportList,
        fetchColumnLoading: fetchColumnLoading,
        formItemLayout: formItemLayout,
        queryFormItem: queryFormItem,
        form: form,
        checkedKeys: checkedKeys,
        expandedKeys: expandedKeys,
        renderQueryForm: this.renderQueryForm,
        renderTreeNodes: this.renderTreeNodes,
        onExpand: this.handleExpand,
        onSelect: this.handleSelect,
        enableAsync: enableAsync,
        exportAsync: exportAsync
      })), /*#__PURE__*/React.createElement(Modal, historyModalProps, /*#__PURE__*/React.createElement(HistoryData, null)));
    }
  }]);

  return ExcelExport;
}(React.PureComponent), (_applyDecoratedDescriptor(_class2.prototype, "queryColumnData", [_dec2], Object.getOwnPropertyDescriptor(_class2.prototype, "queryColumnData"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleExpand", [_dec3], Object.getOwnPropertyDescriptor(_class2.prototype, "handleExpand"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleSelect", [_dec4], Object.getOwnPropertyDescriptor(_class2.prototype, "handleSelect"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleExport", [_dec5, _dec6], Object.getOwnPropertyDescriptor(_class2.prototype, "handleExport"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "traversalTreeNodes", [_dec7], Object.getOwnPropertyDescriptor(_class2.prototype, "traversalTreeNodes"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "renderTreeNodes", [_dec8], Object.getOwnPropertyDescriptor(_class2.prototype, "renderTreeNodes"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "renderQueryForm", [_dec9], Object.getOwnPropertyDescriptor(_class2.prototype, "renderQueryForm"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleMenuClick", [_dec10], Object.getOwnPropertyDescriptor(_class2.prototype, "handleMenuClick"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "showSyncExportModal", [_dec11], Object.getOwnPropertyDescriptor(_class2.prototype, "showSyncExportModal"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "showHistoryModal", [_dec12], Object.getOwnPropertyDescriptor(_class2.prototype, "showHistoryModal"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "hideHistoryModal", [_dec13], Object.getOwnPropertyDescriptor(_class2.prototype, "hideHistoryModal"), _class2.prototype)), _class2)) || _class);
export { ExcelExport as default };